package com.hq.fxh.No5_User.User.Activity;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hq.fxh.CustomerView.PopupWindow.PopupForAddress;
import com.hq.fxh.CustomerView.PopupWindow.PopupForComment;
import com.hq.fxh.CustomerView.PopupWindow.PopupForSexSelect;
import com.hq.fxh.HttpApi.UserServiceImpl;
import com.hq.fxh.Intefers.NetworkSubscriber;
import com.hq.fxh.Modle.MyResponseBody;
import com.hq.fxh.Modle.SelectByMemberIdRes;
import com.hq.fxh.Modle.UserGetModle;
import com.hq.fxh.Modle.UserModle;
import com.hq.fxh.No0_ChengQu.Activity.BaseActivity;
import com.hq.fxh.No3_TuiGuang.MyMoBan.Activity.item.ToastUtils;
import com.hq.fxh.No5_User.CitySelectActivity;
import com.hq.fxh.No6UerSpace.Fragment.Select;
import com.hq.fxh.R;
import com.hq.fxh.Utils.AppConstant;
import com.hq.fxh.Utils.DownPictureUtils;
import com.hq.fxh.Utils.GlideUtils;
import com.hq.fxh.Utils.ImageDownLoadCallBack;
import com.hq.fxh.Utils.LogUtils;
import com.hq.fxh.Utils.PicSelectActivity;
import com.hq.fxh.Utils.SharedPreferenceUtils;
import com.hq.fxh.Utils.Tool;
import com.hq.fxh.Utils.UpLoadUtils;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;

import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static cn.jpush.im.android.api.enums.ContentType.file;
import static cn.jpush.im.android.tasks.GetUserInfoListTask.IDType.uid;
import static com.tencent.download.global.Global.getContext;

public class UserXinXiActivity extends BaseActivity implements View.OnClickListener {

    protected ImageView tvUserSetHeadPic;
    protected TextView tvUserSetName;
    protected TextView tvUserSetMiaoShu;
    protected TextView tvUserSetSex;
    protected TextView tvUserSetBrith;
    protected TextView tvUserSetPhone;
    protected TextView tvUserSetAddress;
    protected ImageView toolbarImageBack;
    protected LinearLayout toolbarLayoutBack;
    protected TextView toolBarTvTitle;
    protected TextView toolBarTvMore;
    protected LinearLayout toolbarLayoutMore;
    protected LinearLayout toolbarContent;
    private PopupForComment customPopupForComment;
    private PopupForSexSelect popupForSexSelect;
    private int[] citys = {R.array.def, R.array.北京, R.array.天津, R.array.河北, R.array.山西, R.array.内蒙古
            , R.array.辽宁, R.array.吉林, R.array.黑龙江, R.array.上海, R.array.江苏
            , R.array.浙江, R.array.安徽, R.array.福建, R.array.江西, R.array.山东
            , R.array.河南, R.array.湖北, R.array.湖南, R.array.广东, R.array.广西
            , R.array.海南, R.array.重庆, R.array.四川, R.array.贵州, R.array.云南
            , R.array.西藏, R.array.陕西, R.array.甘肃, R.array.青海, R.array.宁夏
            , R.array.新疆, R.array.台湾, R.array.香港, R.array.澳门};

    String[] province;
    String[] city;
    private PopupForAddress popupPro;
    private PopupForAddress popupCity;
    UserModle userModle;
    private String picPath;
    String nickName;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_yong_hu_xin_xi;
    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.tv_UserSet_HeadPic) {
            clickAddHeadPic();

        } else if (view.getId() == R.id.tv_UserSet_Name) {
            clickName();
        } else if (view.getId() == R.id.tv_UserSet_MiaoShu) {
            clickMiaoShu();
        } else if (view.getId() == R.id.tv_UserSet_Sex) {
            clickSex();

        } else if (view.getId() == R.id.tv_UserSet_Brith) {
            clickBrith();

        } else if (view.getId() == R.id.tv_UserSet_Phone) {
            clickPhone();

        } else if (view.getId() == R.id.tv_UserSet_Address) {
            clickAddress();

        } else if (view.getId() == R.id.toolbar_Layout_back) {
            finish();

        } else if (view.getId() == R.id.toolbar_Layout_More) {

            clickSave();

        }
    }

    private void clickSave() {

        userModle.setUid(SharedPreferenceUtils.getMemberId(this));
        if (nickName != null) {
            upDataIMName(nickName);
        }

        if (picUrlPath != null) {
            upDataIMPic( );
        }
        upDataUserInfo();

    }

    private void clickSex() {
        if (popupForSexSelect == null) {
            popupForSexSelect = new PopupForSexSelect(this, 0, new PopupForSexSelect.PopSexCallBack() {
                @Override
                public void callSure(int position, String comment) {
                    tvUserSetSex.setText(comment);
                    LogUtils.e("性别: " + position + comment);
                    userModle.setSex(position);
                }
            });
        }
        popupForSexSelect.show(tvUserSetSex);

    }

    private void clickBrith() {
        setTime();
    }

    private void clickPhone() {
        showEdit(tvUserSetPhone, 2);
    }

    private void clickAddress() {
     /*   popupPro.settitle("选择地区");
        popupPro.show(tvUserSetAddress);*/
        startActivityForResult(new Intent(UserXinXiActivity.this, Select.class), AppConstant.CitySelectCode);
    }

    private void clickMiaoShu() {
        showEdit(tvUserSetPhone, 1);
    }

    private void clickName() {
        showEdit(tvUserSetPhone, 0);

    }

    private void clickAddHeadPic() {
        Intent intent = new Intent(UserXinXiActivity.this, PicSelectActivity.class);
        intent.putExtra(AppConstant.maxPic, 1);
        startActivityForResult(intent, AppConstant.PicSelectResultCode);

    }

    void openFinish() {
        finish();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppConstant.PicSelectResultCode && data != null) {

            picPath = data.getStringExtra("data");
            if (picPath != null) {

                setUpPic(picPath);
                GlideUtils.loadImageView(UserXinXiActivity.this, picPath, tvUserSetHeadPic);
            } else {
                LogUtils.startToash(UserXinXiActivity.this, "图片选取失败");
            }
        } else if (requestCode == AppConstant.CitySelectCode && data != null) {
            /*     data1.putExtra("cityName", cityName);
                data1.putExtra("proName", proName);
                data1.putExtra("cityID", cityID);
                data1.putExtra("proID", proID);*/
            int cityID = data.getIntExtra("cityID", 0);
            int proID = data.getIntExtra("proID", 0);
            String proName = data.getStringExtra("proName");
            String cityName = data.getStringExtra("cityName");

            userModle.setCity_id(cityID);
            userModle.setCity(cityName);
            userModle.setProvince_id(proID);
            userModle.setProvince(proName);
            tvUserSetAddress.setText(proName + cityName);
            LogUtils.e("收到的地址信息：" + proName + cityName + "  id:" + proID + "  " + cityID);

        }
    }

    @Override
    protected void initView() {
        tvUserSetHeadPic = (ImageView) findViewById(R.id.tv_UserSet_HeadPic);
        tvUserSetHeadPic.setOnClickListener(UserXinXiActivity.this);
        tvUserSetName = (TextView) findViewById(R.id.tv_UserSet_Name);
        tvUserSetName.setOnClickListener(UserXinXiActivity.this);
        tvUserSetMiaoShu = (TextView) findViewById(R.id.tv_UserSet_MiaoShu);
        tvUserSetMiaoShu.setOnClickListener(UserXinXiActivity.this);
        tvUserSetSex = (TextView) findViewById(R.id.tv_UserSet_Sex);
        tvUserSetSex.setOnClickListener(UserXinXiActivity.this);
        tvUserSetBrith = (TextView) findViewById(R.id.tv_UserSet_Brith);
        tvUserSetBrith.setOnClickListener(UserXinXiActivity.this);
        tvUserSetPhone = (TextView) findViewById(R.id.tv_UserSet_Phone);
        tvUserSetPhone.setOnClickListener(UserXinXiActivity.this);
        tvUserSetAddress = (TextView) findViewById(R.id.tv_UserSet_Address);
        tvUserSetAddress.setOnClickListener(UserXinXiActivity.this);
        toolbarImageBack = (ImageView) findViewById(R.id.toolbar_image_back);
        toolbarLayoutBack = (LinearLayout) findViewById(R.id.toolbar_Layout_back);
        toolbarLayoutBack.setOnClickListener(UserXinXiActivity.this);
        toolBarTvTitle = (TextView) findViewById(R.id.toolBar_tv_Title);
        toolBarTvMore = (TextView) findViewById(R.id.toolBar_tv_More);
        toolbarLayoutMore = (LinearLayout) findViewById(R.id.toolbar_Layout_More);
        toolbarLayoutMore.setOnClickListener(UserXinXiActivity.this);
        toolbarContent = (LinearLayout) findViewById(R.id.toolbar_Content);
        getUserInfo();
        toolBarTvMore.setText("保存");
        toolBarTvTitle.setText("基本信息");
    }


    String ads = null;

    @Override
    protected void initData() {

/*
        Intent intent = getIntent();
        uid = intent.getIntExtra("id", 0);
        Serializable serializable = intent.getSerializableExtra("data");

        if (serializable == null) {
            getMerchantDetails();
        } else {
            data = (SelectByMemberIdRes.DataBean) serializable;
            setViewData();
        }*/
        province = getResources().getStringArray(R.array.province);
        popupPro = new PopupForAddress(UserXinXiActivity.this, province, new PopupForAddress.ShareModleCallBack() {
            @Override
            public void callSure(int position, String comment) {
                popupPro.dismiss();
                Message msg = new Message();
                msg.what = 0;
                Bundle data = new Bundle();
                data.putInt("position", position);
                data.putString("string", comment);
                msg.setData(data);
                handler.sendMessage(msg);
            }
        });
        popupCity = new PopupForAddress(UserXinXiActivity.this, city, new PopupForAddress.ShareModleCallBack() {
            @Override
            public void callSure(int position, String comment) {
                LogUtils.e(comment);
                ads = ads + comment;
                tvUserSetAddress.setText(ads);

                popupCity.dismiss();
            }
        });
        popupPro.setTextType(1);
        popupCity.setTextType(1);

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 0:
                    Bundle data = msg.getData();
                    int position = data.getInt("position");
                    String string = data.getString("string");
                    city = getResources().getStringArray(citys[position]);
                    ads = string;
                    popupCity.setData(city);
                    popupCity.settitle(string);
                    popupCity.show(tvUserSetSex);
                    break;
            }
        }
    };

    private void setTime() {
        final Calendar c = Calendar.getInstance();
        int mYear = c.get(Calendar.YEAR);
        int mMonth = c.get(Calendar.MONTH);
        int mDay = c.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog age = new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        String time = year + "-" + (month + 1) + "-" + dayOfMonth;
                        tvUserSetBrith.setText(time);
                        userModle.setBirth(time);
                    }
                },
                mYear, mMonth, mDay);

        age.show();

    }

    public void showEdit(View view, final int type) {

        customPopupForComment = new PopupForComment(UserXinXiActivity.this, new PopupForComment.CommentCallBack() {
            @Override
            public void call(String comment) {
                if (comment == null || comment.equals("")) {
                    LogUtils.startToash(UserXinXiActivity.this, "填写的信息为空");
                } else {
                    switch (type) {
                        case 0:
                            nickName = comment;
                            tvUserSetName.setText(comment);
                            userModle.setNickname(comment);
                            break;
                        case 1:
                            tvUserSetMiaoShu.setText(comment);
                            userModle.setTag(comment);

                            break;
                        case 2:
                            tvUserSetPhone.setText(comment);
                            userModle.setMobile(comment);


                            break;

                    }
                }


            }
        });

        customPopupForComment.openKeyboard();
        Tool.setAlpha(UserXinXiActivity.this, 0.6f);
        customPopupForComment.showAtLocation(view,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }


    public void setViewData() {
        Tool.setStringToText(tvUserSetName, userModle.getNickname());
        Tool.setStringToText(tvUserSetMiaoShu, userModle.getTag());
        int sex = userModle.getSex();
        LogUtils.e("获取的性别：" + sex);
        if (sex == 1) {
            Tool.setStringToText(tvUserSetSex, "男");
        } else if (sex == 2) {
            Tool.setStringToText(tvUserSetSex, "女");
        } else {
            Tool.setStringToText(tvUserSetSex, "选择性别");
        }
        String birth = userModle.getBirth();
        if (birth != null && birth.length() > 8) {
            birth = birth.substring(0, birth.indexOf(" "));
        }
        Tool.setStringToText(tvUserSetBrith, birth);
        Tool.setStringToText(tvUserSetAddress, userModle.getCity());
        Tool.setStringToText(tvUserSetPhone, userModle.getMobile());

        String faceUrl = userModle.getFace();
        if (!TextUtils.isEmpty(faceUrl)) {
            Tool.setUrlToHeadImage(this, faceUrl, tvUserSetHeadPic);
        }
    }


    public void getUserInfo() {
        int memberId = SharedPreferenceUtils.getMemberId(this);
        if (memberId == 0) {

        } else {
            UserServiceImpl.GetMemberInfoUrl(memberId, new Callback<UserGetModle>() {
                @Override
                public void onResponse(Call<UserGetModle> call, Response<UserGetModle> response) {
                    UserGetModle body = response.body();
                    if (body == null) {
                        try {
                            LogUtils.startToash(UserXinXiActivity.this, "获取信息失败：" + response.errorBody().string());
                            openFinish();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    } else {
                        userModle = body.getData();
                        setViewData();
                    }

                }

                @Override
                public void onFailure(Call<UserGetModle> call, Throwable t) {

                }
            });
        }
    }


    public void upDataUserInfo() {
        UserServiceImpl.UpdateMemberInfoUrl(userModle.getUid() + "", userModle.getSex() + "", userModle.getNickname(), userModle.getFace(), userModle.getProvince(), userModle.getCity(), userModle.getAddress(), userModle.getProvince_id() + "", userModle.getCity_id() + "", userModle.getTag(), userModle.getBirth(), new Callback<MyResponseBody>() {
            @Override
            public void onResponse(Call<MyResponseBody> call, Response<MyResponseBody> response) {
                MyResponseBody body = response.body();
                if (body == null) {
                    try {
                        LogUtils.startToash(UserXinXiActivity.this, "保存失败" + response.errorBody().string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                } else {
                    try {
                        if (body.getCode() == 0) {
                            LogUtils.startToash(UserXinXiActivity.this, "保存成功");
                            openFinish();
                        } else {
                            LogUtils.startToash(UserXinXiActivity.this, "保存失败" + body.getMsg());

                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onFailure(Call<MyResponseBody> call, Throwable t) {
                LogUtils.startToash(UserXinXiActivity.this, "保存错误" + t.getMessage());

            }
        });

    }

    private String picUrlPath;

    public void setUpPic(String picString) {
        UpLoadUtils upLoadUtils = new UpLoadUtils();
        ArrayList<String> picPath = new ArrayList<>();
        picPath.add(picString);
        upLoadUtils.startUpLoadPic(this, picPath, 1, new UpLoadUtils.UpLoadPicCallBack() {


            @Override
            public void onFinishCallBack(ArrayList<String> imageUrl, int tag) {
                if (imageUrl != null) {
                    picUrlPath = imageUrl.get(0);
                    userModle.setFace(picUrlPath);
                    LogUtils.startToash(UserXinXiActivity.this, "设置头像成功");

                } else {
                    LogUtils.startToash(UserXinXiActivity.this, "设置头像出错");
                }
            }

            @Override
            public void onErrorCallBack(int position, Throwable e) {
                LogUtils.startToash(UserXinXiActivity.this, "设置头像出错 " + e.getMessage());

            }
        });

    }


    /**
     * 更新用户IM头像信息
     */
    public void upDataIMPic( ) {

     final    UserInfo myInfo = JMessageClient.getMyInfo();
        if (myInfo == null) {

        } else {
            myInfo.setAddress(picUrlPath);

            JMessageClient.updateMyInfo(UserInfo.Field.address, myInfo, new BasicCallback() {
                @Override
                public void gotResult(int i, String s) {
                    if (i == 0) {
                        //     String picUrl = picList.get(currentPic).getPic_url();
                        Log.i("更新用户昵称信息", "updateNickName," + " responseCode = " + i + "; desc = " + s);
                    } else {

                        Log.i("更新用户昵称信息", "updateNickName," + " responseCode = " + i + "; desc = " + s);
                    }
                }
            });
        }

    }

    /**
     * 更新用户IM昵称
     */
    public void upDataIMName(String nickName) {

        final    UserInfo myInfo = JMessageClient.getMyInfo();
        if (myInfo == null) {

        } else {
            myInfo.setNickname(nickName);

            JMessageClient.updateMyInfo(UserInfo.Field.nickname, myInfo, new BasicCallback() {
                @Override
                public void gotResult(int i, String s) {
                    if (i == 0) {
                        //     String picUrl = picList.get(currentPic).getPic_url();
                        Log.i("更新用户昵称信息", "updateNickName," + " responseCode = " + i + "; desc = " + s);
                    } else {

                        Log.i("更新用户昵称信息", "updateNickName," + " responseCode = " + i + "; desc = " + s);
                    }
                }
            });
        }

    }

}
